package com.lp.util;

import java.io.StringReader;
import java.io.StringWriter;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Iterator;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

public class XmlMarshaller {

	
    public static String beanToXML(Object obj) { 
    	StringWriter writer = new StringWriter(); 
        try {  
            JAXBContext context = JAXBContext.newInstance(obj.getClass());  
            Marshaller marshaller = context.createMarshaller();  
            marshaller.marshal(obj, writer); 
        } catch (JAXBException e) {  
            e.printStackTrace();  
        } 
        return writer.toString();
    } 
    
    
    public static Object XMLStringToBean(String xmlStr, Class<?> target){  
    	Object obj=null;
        try {  
            JAXBContext context = JAXBContext.newInstance(target);  
            Unmarshaller unmarshaller = context.createUnmarshaller();  
            obj= unmarshaller.unmarshal(new StringReader(xmlStr));  
        } catch (JAXBException e) {  
            e.printStackTrace();  
        }  
        return obj;
    }  
    
    
    /**
     * xml字符串转换为java对象:通过反射的机制动态调用set方法
     * @param strXml
     * @param classPath  com.basicwechat.entity.ReceiveXmlEntity
     * @return
     */
    public static Object getMsgEntity(String strXml,Class<?> classz){
        Object msg = null;
        try {
          if (strXml.length() <= 0 || strXml == null)
            return null;
           
          // 将字符串转化为XML文档对象
          Document document = DocumentHelper.parseText(strXml);
          // 获得文档的根节点
          Element root = document.getRootElement();
          // 遍历根节点下所有子节点
          Iterator<?> iter = root.elementIterator();
          
          // 遍历所有结点
          //利用反射机制，调用set方法
          //获取该实体的元类型
          Class<?> c = Class.forName(classz.getName());
          msg = c.newInstance();//创建这个实体的对象
          
          while(iter.hasNext()){
            Element ele = (Element)iter.next();
            //获取set方法中的参数字段（实体类的属性）
//            Field field = c.getDeclaredField(ele.getName());
            Field field =ReflectionUtils.getField(c, ele.getName());
            if(field!=null){
                //获取set方法，field.getType())获取它的参数数据类型
//                Method method = c.getDeclaredMethod("set"+upStr(ele.getName()), field.getType());
                Method method =ReflectionUtils.getMethod(c, "set"+upStr(ele.getName()), field.getType());
                if(method!=null){
                	 Class<?>[] clazz = method.getParameterTypes();  
                     String type = clazz[0].getName();  
                     if(type.equals("java.lang.String")) 
                    	//调用set方法
     	                method.invoke(msg, ele.getText()); 
                     else if(type.equals("java.lang.Integer"))
                         method.invoke(msg, Integer.parseInt(ele.getText())); 
                     else if(type.equals("java.lang.Double"))
                    	 method.invoke(msg, Double.parseDouble(ele.getText())); 
                     else
                    	//调用set方法
       	                method.invoke(msg, ele.getText()); 
                }
            }
          }
        } catch (Exception e) {
        	LogUtil.errorLog("xml 格式异常: "+ strXml);
        	LogUtil.errorLog(e.getMessage());
        }
        return msg;
      }
    
    /**
     * 把字符串首字母转换为大写
     * @param str
     * @return
     */
    public static String upStr(String str){
    	return str.replaceFirst(str.substring(0, 1),str.substring(0, 1).toUpperCase()) ;
    }
    
}
